package com.csdj.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csdj.server.mapper.EmployeeMapper;
import com.csdj.server.pojo.Employee;
import com.csdj.server.pojo.RespBean;
import com.csdj.server.pojo.RespPageBean;
import com.csdj.server.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xyx
 * @since 2022-12-12
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements IEmployeeService {
    @Autowired(required = false)
    private EmployeeMapper employeeMapper;

    @Override
    public RespPageBean getEmployeeByPage(Integer currentPage, Integer size, Employee employee, LocalDate[] beginDateScope) {
        //开启分页
        Page<Employee> page = new Page<>(currentPage, size);
        IPage<Employee> employeePage = employeeMapper.getEmployeeByPage(page, employee, beginDateScope);
        RespPageBean respPageBean = new RespPageBean(employeePage.getTotal(),employeePage.getRecords());
        return respPageBean;
    }

    @Override
    public RespBean maxWorkId() {
        //list 集合 储存的是 一个 map集合
        //map 集合中存放的数据 key -value
        //key = max(wordID) value = 000000100
        List<Map<String, Object>> maps = employeeMapper.selectMaps(new QueryWrapper<Employee>().select("MAX(workID)"));
//        Integer maxWordId = Integer.parseInt(maps.get(0).get("MAX(workID))").toString() + 1);
        //101
        // %08d 解决 转换String类型的时候 出现的乱码
        //补0
        return RespBean.success(null,String.format("%08d",Integer.parseInt(maps.get(0).get("MAX(workID)").toString()) + 1));
    }

    @Override
    public RespBean insertEmp(Employee employee) {
        //获取合同期限的起始日期
        LocalDate beginContract = employee.getBeginContract();
        //合同的期限的结束日期
        LocalDate endContract = employee.getEndContract();
        //计算2个日期之间相差的天数
        long days = beginContract.until(endContract, ChronoUnit.DAYS);
        //指定计算 年限之后 保留两位小数
        DecimalFormat decimalFormat = new DecimalFormat("##.00");
        //设置 合同年限
        employee.setContractTerm(Double.parseDouble(decimalFormat.format(days / 365.00)));
        //新增员工信息
        if(employeeMapper.insert(employee) == 1){
            return RespBean.success("添加成功!");
        }
        return RespBean.error("添加失败!");
    }
}
